import * as Http from "./http";

/**
 * 通过vid获取腾讯视频地址
 * 
 * @param {*} vid 
 * @param {*} endFix 
 * @param {*} prefix 
 */
export function getTecentVideo(vid,
    endFix = `&platform=101001&charge=0&otype=json&defn=hd&defaultfmt=auto`,
    prefix = `https://vv.video.qq.com/getinfo`
) {
  return new Promise(function (resolve, reject) {
    if (!vid) {
        console.error("no vid");
        reject(new Error("no vid"));
    }
    let hdPlatform = endFix;
    Http.get(`${prefix}?vids=${vid}${hdPlatform}`)
        .then(function (res) {
            // console.log(res);
            let JSONDATA = res.replace("QZOutputJson=", "");
            JSONDATA = JSONDATA.slice(0, JSONDATA.length - 1);
            try {
                let videoInfo = JSON.parse(JSONDATA);
                if (videoInfo.msg && videoInfo.msg.indexOf("vid is wrong") > -1) {
                    reject(new Error(videoInfo.msg));
                }
                if (videoInfo.vl && videoInfo.vl.vi) {
                    let videos = videoInfo.vl.vi;
                    let curVideo = videos[0];
                    let fn = curVideo.fn;
                    let fvkey = curVideo.fvkey;
                    let curVideoPlayAddress = "";
                    let playurl = `${fn}?vkey=${fvkey}`;
                    if (curVideo) {
                        if (curVideo.ul && curVideo.ul.ui) {
                        curVideoPlayAddress = curVideo.ul.ui[0];
                        }
                    }
                    console.log(videoInfo);
                    if (curVideoPlayAddress) {
                        playurl = curVideoPlayAddress.url + playurl;
                        resolve(playurl);
                    } else {
                        reject(new Error("no curVideoPlayAddress"));
                    }
                } else {
                    reject(new Error("no videoInfo"));
                }
            } catch (e) {
                console.error(e);
                reject(e);
            }
        }).catch((e)=> {
            console.error(e);
            reject(e);
        })
    })
}

/**
 * 检测当前网络情况 如果是wifi就直接播放 否则调用失败回调
 *
 * @constructor
 */
export function AutoPlayVideo(success, failed) {
    wx.getNetworkType({
      success: function(res) {
        let networkType = res.networkType;
        console.log("cur networkType", networkType);
        if (networkType === "wifi") {
          if (success) {
            success();
          }
        } else {
          if (failed) {
            failed();
          }
        }
      },
      fail() {
        if (failed) {
          failed();
        }
      }
    })
  }